{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Vehicle Recommender Interactive Agent \n",
    "\n",
    "\n",
    "### We are going to Build a Car Recommender Agent\n",
    "\n",
    "🎯 Core Features Implemented\n",
    "\n",
    "**Multi-Agent Architecture**\n",
    "\n",
    "- 4 Specialist Agents: Budget, Family, Luxury, Eco-friendly\n",
    "- 1 Manager Agent: Orchestrates and routes to specialists\n",
    "- 8 Function Tools: Direct inventory search capabilities\n",
    "\n",
    "\n",
    "\n",
    "**Synthetic Data System**\n",
    "- 6 Sample Vehicles: Diverse range (sedan, SUV, truck, electric, luxury)\n",
    "- 4 Customer Personas: Different use cases and priorities\n",
    "- Realistic Attributes: Price, MPG, safety, features, availability"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Imports"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Requirement already satisfied: nest_asyncio in /opt/anaconda3/lib/python3.12/site-packages (1.6.0)\n"
     ]
    }
   ],
   "source": [
    "#!pip install nest_asyncio"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "from dotenv import load_dotenv\n",
    "from agents import Agent, Runner, trace, function_tool\n",
    "from openai.types.responses import ResponseTextDeltaEvent\n",
    "import asyncio\n",
    "from agents import Agent, Runner, trace, function_tool\n",
    "from typing import Dict, List, Optional\n",
    "import json\n",
    "import pandas as pd\n",
    "from datetime import datetime\n",
    "import os\n",
    "import nest_asyncio\n",
    "\n",
    "\n",
    "import nest_asyncio\n",
    "import asyncio\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "nest_asyncio.apply()  # This MUST be called first!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    " ### Jupyter  Notebook Compatibility  fix  for asyncio"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "####  Load environment variables"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "load_dotenv(override=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 1: Synthetic Data Generation \n",
    "\n",
    "- Generate Synthetic Inventory \n",
    "- Generate Synthetic Persona "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "def generate_synthetic_inventory():\n",
    "    \"\"\"Generate synthetic vehicle inventory data\"\"\"\n",
    "    inventory_data = [\n",
    "        {\n",
    "            \"id\": \"V001\",\n",
    "            \"make\": \"Toyota\",\n",
    "            \"model\": \"Camry\",\n",
    "            \"year\": 2024,\n",
    "            \"type\": \"Sedan\",\n",
    "            \"price\": 28000,\n",
    "            \"mpg_city\": 28,\n",
    "            \"mpg_highway\": 39,\n",
    "            \"seating_capacity\": 5,\n",
    "            \"safety_rating\": 5,\n",
    "            \"drivetrain\": \"FWD\",\n",
    "            \"fuel_type\": \"Gasoline\",\n",
    "            \"features\": [\"Backup Camera\", \"Bluetooth\", \"Lane Assist\", \"Adaptive Cruise Control\"],\n",
    "            \"colors_available\": [\"White\", \"Black\", \"Silver\", \"Red\"],\n",
    "            \"availability\": \"in_stock\",\n",
    "            \"stock_count\": 12,\n",
    "            \"category\": \"family\",\n",
    "            \"description\": \"Reliable family sedan with excellent fuel economy and safety features\"\n",
    "        },\n",
    "        {\n",
    "            \"id\": \"V002\", \n",
    "            \"make\": \"Honda\",\n",
    "            \"model\": \"CR-V\",\n",
    "            \"year\": 2024,\n",
    "            \"type\": \"SUV\",\n",
    "            \"price\": 32000,\n",
    "            \"mpg_city\": 27,\n",
    "            \"mpg_highway\": 32,\n",
    "            \"seating_capacity\": 5,\n",
    "            \"safety_rating\": 5,\n",
    "            \"drivetrain\": \"AWD\",\n",
    "            \"fuel_type\": \"Gasoline\",\n",
    "            \"features\": [\"All-Wheel Drive\", \"Cargo Space\", \"Apple CarPlay\", \"Blind Spot Monitor\"],\n",
    "            \"colors_available\": [\"Blue\", \"White\", \"Black\", \"Gray\"],\n",
    "            \"availability\": \"in_stock\",\n",
    "            \"stock_count\": 8,\n",
    "            \"category\": \"suv\",\n",
    "            \"description\": \"Versatile SUV perfect for families and outdoor adventures\"\n",
    "        },\n",
    "        {\n",
    "            \"id\": \"V003\",\n",
    "            \"make\": \"Tesla\",\n",
    "            \"model\": \"Model 3\",\n",
    "            \"year\": 2024,\n",
    "            \"type\": \"Electric Sedan\",\n",
    "            \"price\": 42000,\n",
    "            \"mpg_city\": 0,  # Electric\n",
    "            \"mpg_highway\": 0,  # Electric\n",
    "            \"range_miles\": 310,\n",
    "            \"seating_capacity\": 5,\n",
    "            \"safety_rating\": 5,\n",
    "            \"drivetrain\": \"RWD\",\n",
    "            \"fuel_type\": \"Electric\",\n",
    "            \"features\": [\"Autopilot\", \"Supercharger Network\", \"Over-the-air Updates\", \"Premium Audio\"],\n",
    "            \"colors_available\": [\"White\", \"Black\", \"Blue\", \"Red\"],\n",
    "            \"availability\": \"in_stock\",\n",
    "            \"stock_count\": 5,\n",
    "            \"category\": \"electric\",\n",
    "            \"description\": \"Cutting-edge electric sedan with advanced technology and sustainability\"\n",
    "        },\n",
    "        {\n",
    "            \"id\": \"V004\",\n",
    "            \"make\": \"Ford\",\n",
    "            \"model\": \"F-150\",\n",
    "            \"year\": 2024,\n",
    "            \"type\": \"Pickup Truck\",\n",
    "            \"price\": 38000,\n",
    "            \"mpg_city\": 20,\n",
    "            \"mpg_highway\": 26,\n",
    "            \"seating_capacity\": 6,\n",
    "            \"safety_rating\": 4,\n",
    "            \"drivetrain\": \"4WD\",\n",
    "            \"fuel_type\": \"Gasoline\",\n",
    "            \"features\": [\"Towing Capacity 13200lbs\", \"Bed Liner\", \"4WD\", \"Trailer Assist\"],\n",
    "            \"colors_available\": [\"White\", \"Black\", \"Blue\", \"Red\", \"Silver\"],\n",
    "            \"availability\": \"in_stock\",\n",
    "            \"stock_count\": 15,\n",
    "            \"category\": \"truck\",\n",
    "            \"description\": \"America's best-selling truck with unmatched capability and durability\"\n",
    "        },\n",
    "        {\n",
    "            \"id\": \"V005\",\n",
    "            \"make\": \"BMW\",\n",
    "            \"model\": \"X3\",\n",
    "            \"year\": 2024,\n",
    "            \"type\": \"Luxury SUV\",\n",
    "            \"price\": 48000,\n",
    "            \"mpg_city\": 23,\n",
    "            \"mpg_highway\": 29,\n",
    "            \"seating_capacity\": 5,\n",
    "            \"safety_rating\": 5,\n",
    "            \"drivetrain\": \"AWD\",\n",
    "            \"fuel_type\": \"Gasoline\",\n",
    "            \"features\": [\"Leather Seats\", \"Panoramic Sunroof\", \"Premium Audio\", \"Wireless Charging\"],\n",
    "            \"colors_available\": [\"White\", \"Black\", \"Gray\", \"Blue\"],\n",
    "            \"availability\": \"in_stock\",\n",
    "            \"stock_count\": 6,\n",
    "            \"category\": \"luxury\",\n",
    "            \"description\": \"Luxury SUV combining performance, comfort, and prestige\"\n",
    "        },\n",
    "        {\n",
    "            \"id\": \"V006\",\n",
    "            \"make\": \"Hyundai\",\n",
    "            \"model\": \"Elantra\",\n",
    "            \"year\": 2024,\n",
    "            \"type\": \"Compact Sedan\",\n",
    "            \"price\": 22000,\n",
    "            \"mpg_city\": 33,\n",
    "            \"mpg_highway\": 43,\n",
    "            \"seating_capacity\": 5,\n",
    "            \"safety_rating\": 4,\n",
    "            \"drivetrain\": \"FWD\",\n",
    "            \"fuel_type\": \"Gasoline\",\n",
    "            \"features\": [\"10-year Warranty\", \"Touchscreen\", \"Rear Camera\", \"Smart Key\"],\n",
    "            \"colors_available\": [\"White\", \"Black\", \"Silver\", \"Blue\"],\n",
    "            \"availability\": \"in_stock\",\n",
    "            \"stock_count\": 20,\n",
    "            \"category\": \"budget\",\n",
    "            \"description\": \"Affordable compact sedan with excellent warranty and fuel efficiency\"\n",
    "        }\n",
    "    ]\n",
    "    \n",
    "    # Save to JSON file\n",
    "    with open('data/synthetic_inventory.json', 'w') as f:\n",
    "        json.dump(inventory_data, f, indent=2)\n",
    "    \n",
    "    return inventory_data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "def generate_customer_personas():\n",
    "    \"\"\"Generate synthetic customer personas for testing\"\"\"\n",
    "    personas = [\n",
    "        {\n",
    "            \"name\": \"Young Professional\",\n",
    "            \"budget_max\": 30000,\n",
    "            \"family_size\": 1,\n",
    "            \"priorities\": [\"fuel_economy\", \"technology\", \"style\"],\n",
    "            \"usage\": \"daily_commute\",\n",
    "            \"preferences\": [\"compact\", \"sedan\"],\n",
    "            \"test_query\": \"I need a fuel-efficient car for my daily commute under $30k\"\n",
    "        },\n",
    "        {\n",
    "            \"name\": \"Growing Family\",\n",
    "            \"budget_max\": 40000,\n",
    "            \"family_size\": 4,\n",
    "            \"priorities\": [\"safety\", \"space\", \"reliability\"],\n",
    "            \"usage\": \"family_trips\",\n",
    "            \"preferences\": [\"suv\", \"minivan\"],\n",
    "            \"test_query\": \"I have two kids and need a safe, spacious vehicle for family trips\"\n",
    "        },\n",
    "        {\n",
    "            \"name\": \"Eco-Conscious\",\n",
    "            \"budget_max\": 50000,\n",
    "            \"family_size\": 2,\n",
    "            \"priorities\": [\"environmental\", \"technology\", \"efficiency\"],\n",
    "            \"usage\": \"mixed\",\n",
    "            \"preferences\": [\"electric\", \"hybrid\"],\n",
    "            \"test_query\": \"I want an environmentally friendly car with the latest technology\"\n",
    "        },\n",
    "        {\n",
    "            \"name\": \"Work Contractor\",\n",
    "            \"budget_max\": 45000,\n",
    "            \"family_size\": 1,\n",
    "            \"priorities\": [\"capability\", \"durability\", \"utility\"],\n",
    "            \"usage\": \"work_hauling\",\n",
    "            \"preferences\": [\"truck\", \"van\"],\n",
    "            \"test_query\": \"I need a truck for my construction business that can haul materials\"\n",
    "        }\n",
    "    ]\n",
    "    \n",
    "    with open('data/customer_personas.json', 'w') as f:\n",
    "        json.dump(personas, f, indent=2)\n",
    "    \n",
    "    return personas\n",
    "\n",
    "# ==================="
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Load Inventory data "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load inventory data\n",
    "inventory_df = None\n",
    "\n",
    "def load_inventory():\n",
    "    \"\"\"Load inventory data into pandas DataFrame\"\"\"\n",
    "    global inventory_df\n",
    "    try:\n",
    "        with open('data/synthetic_inventory.json', 'r') as f:\n",
    "            inventory_data = json.load(f)\n",
    "        inventory_df = pd.DataFrame(inventory_data)\n",
    "        return True\n",
    "    except FileNotFoundError:\n",
    "        # Generate synthetic data if file doesn't exist\n",
    "        inventory_data = generate_synthetic_inventory()\n",
    "        inventory_df = pd.DataFrame(inventory_data)\n",
    "        return True\n",
    "    except Exception as e:\n",
    "        print(f\"Error loading inventory: {e}\")\n",
    "        return False"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Tool Definitions \n",
    "- Search vehicles by budget \n",
    "- Search vehicles by type \n",
    "- Search vehicle by features \n",
    "- Get vehicle by fuel efficient features \n",
    "- Get vehicle by safety ratings \n",
    "- Get vehicle by vehicle id \n",
    "- Check inventory availability\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "@function_tool\n",
    "def search_vehicles_by_budget(max_budget: int, min_budget: int = 0) -> List[Dict]:\n",
    "    \"\"\"Search vehicles within specified budget range\"\"\"\n",
    "    if inventory_df is None:\n",
    "        load_inventory()\n",
    "    \n",
    "    filtered = inventory_df[\n",
    "        (inventory_df['price'] >= min_budget) & \n",
    "        (inventory_df['price'] <= max_budget) &\n",
    "        (inventory_df['availability'] == 'in_stock')\n",
    "    ]\n",
    "    \n",
    "    return filtered.to_dict('records')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "@function_tool\n",
    "def search_vehicles_by_type(vehicle_types: List[str]) -> List[Dict]:\n",
    "    \"\"\"Search vehicles by type (sedan, suv, truck, etc.)\"\"\"\n",
    "    if inventory_df is None:\n",
    "        load_inventory()\n",
    "    \n",
    "    # Convert to lowercase for matching\n",
    "    types_lower = [t.lower() for t in vehicle_types]\n",
    "    \n",
    "    filtered = inventory_df[\n",
    "        (inventory_df['type'].str.lower().isin(types_lower) | \n",
    "         inventory_df['category'].str.lower().isin(types_lower)) &\n",
    "        (inventory_df['availability'] == 'in_stock')\n",
    "    ]\n",
    "    \n",
    "    return filtered.to_dict('records')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "@function_tool\n",
    "def search_vehicles_by_features(required_features: List[str]) -> List[Dict]:\n",
    "    \"\"\"Search vehicles that have specific features\"\"\"\n",
    "    if inventory_df is None:\n",
    "        load_inventory()\n",
    "    \n",
    "    def has_features(vehicle_features, required):\n",
    "        vehicle_features_lower = [f.lower() for f in vehicle_features]\n",
    "        required_lower = [f.lower() for f in required]\n",
    "        return any(req in ' '.join(vehicle_features_lower) for req in required_lower)\n",
    "    \n",
    "    filtered = inventory_df[\n",
    "        inventory_df['features'].apply(lambda x: has_features(x, required_features)) &\n",
    "        (inventory_df['availability'] == 'in_stock')\n",
    "    ]\n",
    "    \n",
    "    return filtered.to_dict('records')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "@function_tool\n",
    "def get_fuel_efficient_vehicles(min_mpg: int = 30) -> List[Dict]:\n",
    "    \"\"\"Get vehicles with fuel efficiency above specified MPG\"\"\"\n",
    "    if inventory_df is None:\n",
    "        load_inventory()\n",
    "    \n",
    "    # For electric vehicles, consider them highly efficient\n",
    "    filtered = inventory_df[\n",
    "        (((inventory_df['mpg_city'] + inventory_df['mpg_highway']) / 2 >= min_mpg) |\n",
    "         (inventory_df['fuel_type'] == 'Electric')) &\n",
    "        (inventory_df['availability'] == 'in_stock')\n",
    "    ]\n",
    "    \n",
    "    return filtered.to_dict('records')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "@function_tool\n",
    "def get_vehicles_by_safety_rating(min_rating: int = 4) -> List[Dict]:\n",
    "    \"\"\"Get vehicles with minimum safety rating\"\"\"\n",
    "    if inventory_df is None:\n",
    "        load_inventory()\n",
    "    \n",
    "    filtered = inventory_df[\n",
    "        (inventory_df['safety_rating'] >= min_rating) &\n",
    "        (inventory_df['availability'] == 'in_stock')\n",
    "    ]\n",
    "    \n",
    "    return filtered.to_dict('records')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "@function_tool\n",
    "def get_vehicle_details(vehicle_id: str) -> Dict:\n",
    "    \"\"\"Get detailed information about a specific vehicle\"\"\"\n",
    "    if inventory_df is None:\n",
    "        load_inventory()\n",
    "    \n",
    "    vehicle = inventory_df[inventory_df['id'] == vehicle_id]\n",
    "    if not vehicle.empty:\n",
    "        return vehicle.iloc[0].to_dict()\n",
    "    return {\"error\": \"Vehicle not found\"}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "@function_tool\n",
    "def compare_vehicles(vehicle_ids: List[str]) -> Dict:\n",
    "    \"\"\"Compare multiple vehicles side by side\"\"\"\n",
    "    if inventory_df is None:\n",
    "        load_inventory()\n",
    "    \n",
    "    vehicles = inventory_df[inventory_df['id'].isin(vehicle_ids)]\n",
    "    comparison = {\n",
    "        \"vehicles\": vehicles.to_dict('records'),\n",
    "        \"comparison_summary\": {\n",
    "            \"price_range\": f\"${vehicles['price'].min():,} - ${vehicles['price'].max():,}\",\n",
    "            \"best_mpg\": vehicles.loc[vehicles['mpg_city'].idxmax(), 'model'] if not vehicles.empty else \"N/A\",\n",
    "            \"highest_safety\": vehicles.loc[vehicles['safety_rating'].idxmax(), 'model'] if not vehicles.empty else \"N/A\"\n",
    "        }\n",
    "    }\n",
    "    return comparison"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "@function_tool\n",
    "def check_inventory_availability(vehicle_id: str) -> Dict:\n",
    "    \"\"\"Check real-time availability and stock count for a vehicle\"\"\"\n",
    "    if inventory_df is None:\n",
    "        load_inventory()\n",
    "    \n",
    "    vehicle = inventory_df[inventory_df['id'] == vehicle_id]\n",
    "    if not vehicle.empty:\n",
    "        return {\n",
    "            \"vehicle_id\": vehicle_id,\n",
    "            \"availability\": vehicle.iloc[0]['availability'],\n",
    "            \"stock_count\": vehicle.iloc[0]['stock_count'],\n",
    "            \"estimated_delivery\": \"2-3 weeks\" if vehicle.iloc[0]['stock_count'] > 0 else \"6-8 weeks\"\n",
    "        }\n",
    "    return {\"error\": \"Vehicle not found\"}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Create Agents \n",
    "\n",
    "\n",
    "####  Prepare Tools List "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Tools list for agents\n",
    "vehicle_tools = [\n",
    "    search_vehicles_by_budget,\n",
    "    search_vehicles_by_type, \n",
    "    search_vehicles_by_features,\n",
    "    get_fuel_efficient_vehicles,\n",
    "    get_vehicles_by_safety_rating,\n",
    "    get_vehicle_details,\n",
    "    compare_vehicles,\n",
    "    check_inventory_availability\n",
    "]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Create Budget Vehicles Focussed Agent "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Budget-focused agent\n",
    "budget_specialist = Agent(\n",
    "    name=\"Budget Vehicle Specialist\",\n",
    "    instructions=\"\"\"You are a budget-conscious vehicle specialist who helps customers find the best value vehicles within their price range. \n",
    "    \n",
    "    You excel at:\n",
    "    - Finding vehicles that maximize value for money\n",
    "    - Identifying cost-effective options with good reliability\n",
    "    - Explaining total cost of ownership\n",
    "    - Highlighting vehicles with good resale value\n",
    "    \n",
    "    Always use the search tools to find current inventory and provide specific vehicle recommendations with pricing details.\"\"\",\n",
    "    tools=vehicle_tools,\n",
    "    model=\"gpt-4o-mini\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Family Focused Agent "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "# Family-focused agent  \n",
    "family_specialist = Agent(\n",
    "    name=\"Family Vehicle Specialist\", \n",
    "    instructions=\"\"\"You are a family vehicle specialist who prioritizes safety, space, and practicality for families.\n",
    "    \n",
    "    You excel at:\n",
    "    - Recommending vehicles based on family size and needs\n",
    "    - Prioritizing safety ratings and family-friendly features\n",
    "    - Considering cargo space, seating capacity, and convenience features\n",
    "    - Understanding child safety requirements and accessibility\n",
    "    \n",
    "    Always use search tools to find vehicles that meet family requirements and emphasize safety ratings and practical features.\"\"\",\n",
    "    tools=vehicle_tools,\n",
    "    model=\"gpt-4o-mini\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Luxury Vehicle Agent "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Performance/Luxury specialist\n",
    "luxury_specialist = Agent(\n",
    "    name=\"Luxury & Performance Specialist\",\n",
    "    instructions=\"\"\"You are a luxury and performance vehicle specialist who focuses on premium features, advanced technology, and driving experience.\n",
    "    \n",
    "    You excel at:\n",
    "    - Recommending vehicles with premium features and materials\n",
    "    - Understanding performance specifications and driving dynamics  \n",
    "    - Highlighting advanced technology and luxury amenities\n",
    "    - Explaining the value proposition of premium vehicles\n",
    "    \n",
    "    Use search tools to find vehicles with luxury features and provide detailed explanations of premium benefits.\"\"\",\n",
    "    tools=vehicle_tools,\n",
    "    model=\"gpt-4o-mini\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Eco friendly vehicle specialist Agent "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Eco-friendly specialist\n",
    "eco_specialist = Agent(\n",
    "    name=\"Eco-Friendly Vehicle Specialist\",\n",
    "    instructions=\"\"\"You are an eco-friendly vehicle specialist focused on environmental impact, fuel efficiency, and sustainable transportation.\n",
    "    \n",
    "    You excel at:\n",
    "    - Recommending electric, hybrid, and high-efficiency vehicles\n",
    "    - Explaining environmental benefits and cost savings\n",
    "    - Understanding charging infrastructure and range considerations\n",
    "    - Calculating long-term fuel/energy cost savings\n",
    "    \n",
    "    Always prioritize vehicles with the best environmental credentials and use tools to find the most efficient options.\"\"\",\n",
    "    tools=vehicle_tools,\n",
    "    model=\"gpt-4o-mini\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Convert specialist agents to tools \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Convert specialist agents to tools\n",
    "budget_tool = budget_specialist.as_tool(\n",
    "    tool_name=\"budget_specialist\",\n",
    "    tool_description=\"Get budget-focused vehicle recommendations and value analysis\"\n",
    ")\n",
    "\n",
    "family_tool = family_specialist.as_tool(\n",
    "    tool_name=\"family_specialist\", \n",
    "    tool_description=\"Get family-oriented vehicle recommendations focusing on safety and practicality\"\n",
    ")\n",
    "\n",
    "luxury_tool = luxury_specialist.as_tool(\n",
    "    tool_name=\"luxury_specialist\",\n",
    "    tool_description=\"Get luxury and performance vehicle recommendations\"\n",
    ")\n",
    "\n",
    "eco_tool = eco_specialist.as_tool(\n",
    "    tool_name=\"eco_specialist\",\n",
    "    tool_description=\"Get eco-friendly and fuel-efficient vehicle recommendations\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Main Orchestrating Agent "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Main orchestrating agent\n",
    "vehicle_recommendation_agent = Agent(\n",
    "    name=\"Vehicle Recommendation Manager\",\n",
    "    instructions=\"\"\"You are the main vehicle recommendation manager who helps customers find their perfect vehicle.\n",
    "\n",
    "    Your process:\n",
    "    1. Understand the customer's needs, budget, and priorities\n",
    "    2. Determine which specialist agent(s) would be most helpful\n",
    "    3. Use appropriate specialist tools to get recommendations\n",
    "    4. Use direct search tools when needed for specific queries\n",
    "    5. Synthesize recommendations from multiple sources\n",
    "    6. Provide clear, actionable advice with specific vehicle suggestions\n",
    "\n",
    "    Customer Priority Categories:\n",
    "    - Budget-conscious → Use budget_specialist\n",
    "    - Family needs → Use family_specialist  \n",
    "    - Luxury/performance → Use luxury_specialist\n",
    "    - Environmental/efficiency → Use eco_specialist\n",
    "\n",
    "    Always provide:\n",
    "    - At least 2-3 specific vehicle recommendations\n",
    "    - Clear reasoning for each recommendation\n",
    "    - Price information and key features\n",
    "    - Next steps for the customer\n",
    "\n",
    "    Be conversational, helpful, and thorough in your recommendations.\"\"\",\n",
    "    tools=vehicle_tools + [budget_tool, family_tool, luxury_tool, eco_tool],\n",
    "    model=\"gpt-4o-mini\"\n",
    ")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Define Testing  code for  Recommender Agent \n",
    "\n",
    "\n",
    "Here we develop a test framework with some pre loaded queries to test the Vehicle Recommendation  Agent "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [],
   "source": [
    "async def test_multiple_queries_async():\n",
    "    \"\"\"Test multiple queries asynchronously\"\"\"\n",
    "    \n",
    "    if not load_inventory():\n",
    "        generate_synthetic_inventory()\n",
    "        load_inventory()\n",
    "    \n",
    "    test_queries = [\n",
    "        \"I need a reliable family car under $30k\",\n",
    "        \"Show me luxury SUVs with advanced technology\",\n",
    "        \"What's the most fuel-efficient vehicle you have?\",\n",
    "        \"I need a truck for my construction business\"\n",
    "    ]\n",
    "    \n",
    "    print(\"=== TESTING MULTIPLE QUERIES ===\\\\n\")\n",
    "    \n",
    "    for i, query in enumerate(test_queries, 1):\n",
    "        print(f\"Test {i}: {query}\")\n",
    "        print(\"-\" * 50)\n",
    "        \n",
    "        try:\n",
    "            with trace(f\"Test Query {i}\"):\n",
    "                result = await Runner.run(vehicle_recommendation_agent, query)\n",
    "                print(f\"Response: {result.final_output}\\\\n\")\n",
    "        except Exception as e:\n",
    "            print(f\"Error: {e}\\\\n\")\n",
    "        \n",
    "        print(\"=\" * 80 + \"\\\\n\")\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [],
   "source": [
    "async def test_vehicle_agent():\n",
    "    \"\"\"Test the vehicle recommendation agent with sample queries\"\"\"\n",
    "    \n",
    "    # Ensure data is loaded\n",
    "    load_inventory()\n",
    "    generate_customer_personas()\n",
    "    \n",
    "    test_queries = [\n",
    "        \"I need a reliable family car with good fuel economy under $30k\",\n",
    "        \"Looking for a luxury SUV with latest technology features\",\n",
    "        \"What's the most environmentally friendly vehicle you have?\",\n",
    "        \"I need a truck for my construction business that can haul materials\",\n",
    "        \"Show me your most affordable cars with good safety ratings\"\n",
    "    ]\n",
    "    \n",
    "    print(\"=== TESTING VEHICLE RECOMMENDATION AGENT ===\\n\")\n",
    "    \n",
    "    for i, query in enumerate(test_queries, 1):\n",
    "        print(f\"Test {i}: {query}\")\n",
    "        print(\"-\" * 50)\n",
    "        \n",
    "        with trace(f\"Vehicle Recommendation Test {i}\"):\n",
    "            result = await Runner.run(vehicle_recommendation_agent, query)\n",
    "            print(result.final_output)\n",
    "        \n",
    "        print(\"\\n\" + \"=\"*80 + \"\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Define Test code framework for individual specialist Agents \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [],
   "source": [
    "async def demo_specialist_agents():\n",
    "    \"\"\"Demo individual specialist agents\"\"\"\n",
    "    \n",
    "    load_inventory()\n",
    "    \n",
    "    print(\"=== TESTING SPECIALIST AGENTS ===\\n\")\n",
    "    \n",
    "    # Test budget specialist\n",
    "    print(\"1. BUDGET SPECIALIST TEST\")\n",
    "    print(\"-\" * 30)\n",
    "    budget_query = \"Find me the best value car under $25,000\"\n",
    "    \n",
    "    with trace(\"Budget Specialist Demo\"):\n",
    "        result = await Runner.run(budget_specialist, budget_query)\n",
    "        print(f\"Query: {budget_query}\")\n",
    "        print(f\"Response: {result.final_output}\")\n",
    "    \n",
    "    print(\"\\n\" + \"=\"*50 + \"\\n\")\n",
    "    \n",
    "    # Test family specialist  \n",
    "    print(\"2. FAMILY SPECIALIST TEST\")\n",
    "    print(\"-\" * 30)\n",
    "    family_query = \"I have 3 kids and need a safe vehicle for school runs\"\n",
    "    \n",
    "    with trace(\"Family Specialist Demo\"):\n",
    "        result = await Runner.run(family_specialist, family_query)\n",
    "        print(f\"Query: {family_query}\")\n",
    "        print(f\"Response: {result.final_output}\")\n",
    "    \n",
    "    print(\"\\n\" + \"=\"*50 + \"\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Define code for running interactive demo of the Vehicle Reccomendation System \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [],
   "source": [
    "async def run_interactive_demo_async():\n",
    "    \"\"\"Working interactive demo for Jupyter\"\"\"\n",
    "    \n",
    "    print(\"=== INTERACTIVE VEHICLE RECOMMENDATION DEMO ===\")\n",
    "    print(\"Ask me about vehicles! (type 'quit' to exit)\\n\")\n",
    "    \n",
    "    if not load_inventory():\n",
    "        generate_synthetic_inventory()\n",
    "        load_inventory()\n",
    "    \n",
    "    print(f\"✅ Inventory loaded: {len(inventory_df)} vehicles available\\n\")\n",
    "    \n",
    "    while True:\n",
    "        user_input = input(\"You: \").strip()\n",
    "        \n",
    "        if user_input.lower() in ['quit', 'exit', 'stop']:\n",
    "            print(\"Thanks for using the Vehicle Recommendation System!\")\n",
    "            break\n",
    "            \n",
    "        if not user_input:\n",
    "            continue\n",
    "            \n",
    "        print(\"\\nAgent: Thinking...\")\n",
    "        \n",
    "        try:\n",
    "            result = await Runner.run(vehicle_recommendation_agent, user_input)\n",
    "            print(f\"Agent: {result.final_output}\\n\")\n",
    "            \n",
    "        except Exception as e:\n",
    "            print(f\"Error: {e}\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Main Driver Code "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create Directry if does not exist  \n",
    "os.makedirs('data', exist_ok=True)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Display Menu options "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Vehicle Recommendation Agent System\n",
      "========================================\n",
      "1. Testing individual components\n",
      "2. Running full system tests\n",
      "3. Interactive demo\n",
      "\n"
     ]
    }
   ],
   "source": [
    "print(\"Vehicle Recommendation Agent System\")\n",
    "print(\"=\" * 40)\n",
    "print(\"1. Testing individual components\")\n",
    "print(\"2. Running full system tests\") \n",
    "print(\"3. Interactive demo\")\n",
    "print()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Quick Test "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "### Summary of Recommendations\n",
      "\n",
      "1. **Honda CR-V**\n",
      "   - **Price:** $32,000\n",
      "   - **Seating Capacity:** 5\n",
      "   - **Safety Rating:** 5/5\n",
      "   - **Key Features:** AWD, ample cargo space, Apple CarPlay, blind spot monitor.\n",
      "   - **Description:** A versatile SUV perfect for families and outdoor adventures, ensuring both comfort and safety.\n",
      "   - **Availability:** 8 units in stock.\n",
      "   - **Colors:** Blue, White, Black, Gray.\n",
      "\n",
      "2. **Toyota Camry** (if considering a sedan alternative)\n",
      "   - **Price:** $28,000\n",
      "   - **Seating Capacity:** 5\n",
      "   - **Safety Rating:** 5/5\n",
      "   - **Key Features:** Backup camera, Bluetooth, lane assist, adaptive cruise control.\n",
      "   - **Description:** Reliable with excellent fuel economy, making it suitable for family trips.\n",
      "   - **Availability:** 12 units in stock.\n",
      "   - **Colors:** White, Black, Silver, Red.\n",
      "\n",
      "### Next Steps\n",
      "- **Test Drive:** Would you like to schedule a test drive for the Honda CR-V? It's a great way to experience its comfort and features firsthand.\n",
      "- **Options:** If you're interested in exploring other SUVs, I can search for additional options within your budget.\n",
      "- **Financing:** Would you like assistance with financing options or trade-in evaluations?\n",
      "\n",
      "Feel free to ask any further questions or let me know how you'd like to proceed!\n"
     ]
    }
   ],
   "source": [
    "# Quick test - just run this cell\n",
    "async def quick_test():\n",
    "    load_inventory()\n",
    "    result = await Runner.run(vehicle_recommendation_agent, \"I need a family SUV under $35k\")\n",
    "    print(result.final_output)\n",
    "\n",
    "await quick_test()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Test Multiple Queries "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "=== TESTING MULTIPLE QUERIES ===\\n\n",
      "Test 1: I need a reliable family car under $30k\n",
      "--------------------------------------------------\n",
      "Response: Here are some reliable family cars under $30,000 that I highly recommend:\n",
      "\n",
      "### 1. **2024 Toyota Camry**\n",
      "- **Price:** $28,000\n",
      "- **Type:** Sedan\n",
      "- **Seating Capacity:** 5\n",
      "- **Safety Rating:** 5/5\n",
      "- **Fuel Efficiency:** \n",
      "  - City: 28 MPG\n",
      "  - Highway: 39 MPG\n",
      "- **Key Features:**\n",
      "  - Backup Camera\n",
      "  - Bluetooth Connectivity\n",
      "  - Lane Assist\n",
      "  - Adaptive Cruise Control\n",
      "- **Availability:** In stock (12 units)\n",
      "\n",
      "**Why Choose This?**\n",
      "The Camry is a well-rounded family sedan known for its reliability, safety, and great fuel economy. It's spacious enough for family outings and has excellent tech features to keep everyone connected.\n",
      "\n",
      "---\n",
      "\n",
      "### 2. **2024 Hyundai Elantra**\n",
      "- **Price:** $22,000\n",
      "- **Type:** Compact Sedan\n",
      "- **Seating Capacity:** 5\n",
      "- **Safety Rating:** 4/5\n",
      "- **Fuel Efficiency:** \n",
      "  - City: 33 MPG\n",
      "  - Highway: 43 MPG\n",
      "- **Key Features:**\n",
      "  - 10-Year Warranty\n",
      "  - 10.25-Inch Touchscreen\n",
      "  - Rearview Camera\n",
      "  - Smart Key with Push Button Start\n",
      "- **Availability:** In stock (20 units)\n",
      "\n",
      "**Why Choose This?**\n",
      "The Elantra offers excellent fuel efficiency and an expansive warranty, making it a smart choice for budget-conscious families. Its compact size also makes it easy to maneuver in urban settings while providing sufficient room for passengers and cargo.\n",
      "\n",
      "---\n",
      "\n",
      "### 3. **2024 Honda CR-V**\n",
      "- **Price:** Starting around $29,000\n",
      "- **Type:** SUV\n",
      "- **Seating Capacity:** 5\n",
      "- **Safety Rating:** 5/5\n",
      "- **Fuel Efficiency:** \n",
      "  - City: 28 MPG\n",
      "  - Highway: 34 MPG\n",
      "- **Key Features:**\n",
      "  - All-Wheel Drive Available\n",
      "  - Rear Camera\n",
      "  - Honda Sensing Suite (Safety Tech)\n",
      "  - Spacious Cargo Area\n",
      "- **Availability:** Limited stock (8 units)\n",
      "\n",
      "**Why Choose This?**\n",
      "The CR-V is ideal for families needing more space without compromising on safety or efficiency. It combines SUV-like utility with the comfort of a sedan.\n",
      "\n",
      "---\n",
      "\n",
      "### Next Steps:\n",
      "1. **Test Drives:** Consider scheduling test drives for the vehicles you’re interested in to see how they fit your family’s needs.\n",
      "2. **Explore Financing Options:** Reviewing financing options or leasing could help you stay within budget.\n",
      "3. **Ask Questions:** If you have any specific features in mind or need more options, feel free to ask!\n",
      "\n",
      "Would you like more information on any of these vehicles or assistance with something else?\\n\n",
      "================================================================================\\n\n",
      "Test 2: Show me luxury SUVs with advanced technology\n",
      "--------------------------------------------------\n",
      "Response: Here’s a top luxury SUV recommendation that features advanced technology:\n",
      "\n",
      "### **2024 BMW X3**\n",
      "- **Price**: $48,000\n",
      "- **Seating Capacity**: 5\n",
      "- **Fuel Economy**: 23 MPG city / 29 MPG highway\n",
      "- **Drivetrain**: All-Wheel Drive (AWD)\n",
      "- **Safety Rating**: 5 stars\n",
      "\n",
      "#### **Premium Features**\n",
      "- **Leather Seats**: Offers a luxurious and durable interior.\n",
      "- **Panoramic Sunroof**: Enhances the spacious feel with natural light.\n",
      "- **Premium Audio System**: High-fidelity sound for an immersive driving experience.\n",
      "- **Wireless Charging**: Eliminate cable clutter with convenient wireless charging for compatible devices.\n",
      "\n",
      "#### **Advanced Technology**\n",
      "- **Smart Navigation**: Real-time traffic updates and voice command for easy navigation.\n",
      "- **Driving Assistance Features**: Includes adaptive cruise control, lane-keeping assist, and parking assistance for enhanced safety.\n",
      "- **Infotainment System**: A large touchscreen for seamless smartphone integration.\n",
      "\n",
      "#### **Driving Experience**\n",
      "The BMW X3 is celebrated for its dynamic performance and balanced ride, ideal for daily commutes and long road trips. The luxury materials add to comfort and elevate the entire driving experience.\n",
      "\n",
      "#### **Availability**\n",
      "- **Stock Count**: 6 units available\n",
      "\n",
      "If you're interested in exploring more options or specific features, just let me know!\\n\n",
      "================================================================================\\n\n",
      "Test 3: What's the most fuel-efficient vehicle you have?\n",
      "--------------------------------------------------\n",
      "Response: Here are the most fuel-efficient vehicles currently available:\n",
      "\n",
      "### 1. **Toyota Camry (2024)**\n",
      "- **Type:** Sedan\n",
      "- **Price:** $28,000\n",
      "- **Fuel Efficiency:** 28 MPG (City) / 39 MPG (Highway)\n",
      "- **Safety Rating:** 5\n",
      "- **Seating Capacity:** 5\n",
      "- **Key Features:**\n",
      "  - Backup Camera\n",
      "  - Bluetooth\n",
      "  - Lane Assist\n",
      "  - Adaptive Cruise Control\n",
      "- **Description:** A reliable family sedan known for its excellent fuel economy and safety features.\n",
      "- **Availability:** In stock (12 units available)\n",
      "\n",
      "---\n",
      "\n",
      "### 2. **Tesla Model 3 (2024)**\n",
      "- **Type:** Electric Sedan\n",
      "- **Price:** $42,000\n",
      "- **Range:** 310 miles on a full charge\n",
      "- **Safety Rating:** 5\n",
      "- **Seating Capacity:** 5\n",
      "- **Key Features:**\n",
      "  - Autopilot\n",
      "  - Supercharger Network\n",
      "  - Over-the-air Updates\n",
      "  - Premium Audio\n",
      "- **Description:** A cutting-edge electric sedan featuring advanced technology and a focus on sustainability.\n",
      "- **Availability:** In stock (5 units available)\n",
      "\n",
      "---\n",
      "\n",
      "### 3. **Hyundai Elantra (2024)**\n",
      "- **Type:** Compact Sedan\n",
      "- **Price:** $22,000\n",
      "- **Fuel Efficiency:** 33 MPG (City) / 43 MPG (Highway)\n",
      "- **Safety Rating:** 4\n",
      "- **Seating Capacity:** 5\n",
      "- **Key Features:**\n",
      "  - 10-year Warranty\n",
      "  - Touchscreen\n",
      "  - Rear Camera\n",
      "  - Smart Key\n",
      "- **Description:** An affordable compact sedan with outstanding warranty and impressive fuel efficiency.\n",
      "- **Availability:** In stock (20 units available)\n",
      "\n",
      "---\n",
      "\n",
      "### Next Steps:\n",
      "- **Consider Your Needs:** Think about whether you prefer a sedan with gasoline engines like the Camry or Elantra, or if an electric vehicle suits your lifestyle better (like the Tesla Model 3).\n",
      "- **Schedule a Test Drive:** You can visit a dealership or contact them to set up a test drive for any of these vehicles.\n",
      "- **Ask about Financing Options:** If you're interested, inquire about financing options available for each vehicle.\n",
      "\n",
      "Let me know if you need more information or would like to explore other options!\\n\n",
      "================================================================================\\n\n",
      "Test 4: I need a truck for my construction business\n",
      "--------------------------------------------------\n",
      "Response: Got it! For your construction business, you'll likely need a truck that offers durability, towing capacity, and a good payload capacity. \n",
      "\n",
      "To better assist you, could you provide me with your budget range and any specific features you're looking for, such as four-wheel drive, crew cab options, or any particular towing capacity?\\n\n",
      "================================================================================\\n\n"
     ]
    }
   ],
   "source": [
    "await test_multiple_queries_async()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Test Specialist Agents "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [],
   "source": [
    "async def test_specialist_agents_async():\n",
    "    \"\"\"Test individual specialist agents\"\"\"\n",
    "    \n",
    "    if not load_inventory():\n",
    "        generate_synthetic_inventory()\n",
    "        load_inventory()\n",
    "    \n",
    "    print(\"=== TESTING SPECIALIST AGENTS ===\\\\n\")\n",
    "    \n",
    "    agents_and_queries = [\n",
    "        (budget_specialist, \"Find me the best value car under $25,000\"),\n",
    "        (family_specialist, \"I have 3 kids and need a safe vehicle\"),\n",
    "        (luxury_specialist, \"Show me your most premium vehicles\"),\n",
    "        (eco_specialist, \"What's your most environmentally friendly option?\")\n",
    "    ]\n",
    "    \n",
    "    for agent, query in agents_and_queries:\n",
    "        print(f\"🤖 Testing {agent.name}\")\n",
    "        print(f\"Query: {query}\")\n",
    "        print(\"-\" * 40)\n",
    "        \n",
    "        try:\n",
    "            result = await Runner.run(agent, query)\n",
    "            print(f\"Response: {result.final_output[:300]}...\")\n",
    "        except Exception as e:\n",
    "            print(f\"Error: {e}\")\n",
    "        \n",
    "        print(\"\\\\n\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "=== TESTING SPECIALIST AGENTS ===\\n\n",
      "🤖 Testing Budget Vehicle Specialist\n",
      "Query: Find me the best value car under $25,000\n",
      "----------------------------------------\n",
      "Response: Here’s a great value option under $25,000:\n",
      "\n",
      "### 2024 Hyundai Elantra\n",
      "- **Price:** $22,000\n",
      "- **Type:** Compact Sedan\n",
      "- **MPG:** 33 City / 43 Highway\n",
      "- **Seating Capacity:** 5\n",
      "- **Safety Rating:** 4 stars\n",
      "- **Drivetrain:** Front-Wheel Drive (FWD)\n",
      "- **Fuel Type:** Gasoline\n",
      "\n",
      "#### Key Features:\n",
      "- 10-year...\n",
      "\\n\n",
      "🤖 Testing Family Vehicle Specialist\n",
      "Query: I have 3 kids and need a safe vehicle\n",
      "----------------------------------------\n",
      "Response: To assist you better, could you please specify any preferences regarding the type of vehicle you're looking for? For example, are you interested in an SUV, minivan, or another type? Additionally, are there any specific features or a budget in mind?...\n",
      "\\n\n",
      "🤖 Testing Luxury & Performance Specialist\n",
      "Query: Show me your most premium vehicles\n",
      "----------------------------------------\n",
      "Response: Here are some of the most premium vehicles available that incorporate luxury features and advanced technology:\n",
      "\n",
      "### 1. **Tesla Model 3 (2024)**\n",
      "- **Type:** Electric Sedan\n",
      "- **Price:** $42,000\n",
      "- **Seating Capacity:** 5\n",
      "- **Safety Rating:** 5 Stars\n",
      "- **Features:**\n",
      "  - **Autopilot:** Advanced driver as...\n",
      "\\n\n",
      "🤖 Testing Eco-Friendly Vehicle Specialist\n",
      "Query: What's your most environmentally friendly option?\n",
      "----------------------------------------\n",
      "Response: To find the most environmentally friendly vehicle options, I'll focus on electric vehicles (EVs) and hybrids, as they typically have lower emissions and use less fuel. \n",
      "\n",
      "Would you like to specify a budget range or particular features you're looking for in an eco-friendly vehicle?...\n",
      "\\n\n"
     ]
    }
   ],
   "source": [
    "await test_specialist_agents_async()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Complete System  Test "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "async def complete_system_test():\n",
    "    \"\"\"Test tools through the agent instead of directly\"\"\"\n",
    "    \n",
    "    print(\"🔧 Testing Tools Through Agent\")\n",
    "    print(\"-\" * 30)\n",
    "    \n",
    "    # Load inventory\n",
    "    load_inventory()\n",
    "    print(f\"✅ Inventory loaded: {len(inventory_df)} vehicles\")\n",
    "    \n",
    "    # Test tools by asking the agent to use them\n",
    "    test_queries = [\n",
    "        \"Show me cars between $20k and $30k\",  # Tests budget search tool\n",
    "        \"What SUVs do you have?\",              # Tests type search tool\n",
    "        \"Show me cars with high safety ratings\" # Tests safety search tool\n",
    "    ]\n",
    "    \n",
    "    for i, query in enumerate(test_queries, 1):\n",
    "        print(f\"\\\\n{i}. Testing: '{query}'\")\n",
    "        try:\n",
    "            result = await Runner.run(vehicle_recommendation_agent, query)\n",
    "            print(f\"   ✅ Success: {result.final_output[:100]}...\")\n",
    "        except Exception as e:\n",
    "            print(f\"   ❌ Failed: {e}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "🔧 Testing Tools Through Agent\n",
      "------------------------------\n",
      "✅ Inventory loaded: 6 vehicles\n",
      "\\n1. Testing: 'Show me cars between $20k and $30k'\n",
      "   ✅ Success: Here are some great vehicle options in the price range of $20,000 to $30,000:\n",
      "\n",
      "### 1. **Toyota Camry...\n",
      "\\n2. Testing: 'What SUVs do you have?'\n",
      "   ✅ Success: Here’s an SUV that I found for you:\n",
      "\n",
      "### 2024 Honda CR-V\n",
      "- **Price**: $32,000\n",
      "- **MPG**: 27 city / 3...\n",
      "\\n3. Testing: 'Show me cars with high safety ratings'\n",
      "   ✅ Success: Could you please let me know the minimum safety rating you are looking for? The ratings typically ra...\n"
     ]
    }
   ],
   "source": [
    "await complete_system_test()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### test Interactive Demo "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "=== INTERACTIVE VEHICLE RECOMMENDATION DEMO ===\n",
      "Ask me about vehicles! (type 'quit' to exit)\n",
      "\n",
      "✅ Inventory loaded: 6 vehicles available\n",
      "\n",
      "\n",
      "Agent: Thinking...\n",
      "Agent: To better assist you, could you please provide me with your budget range? This would help me find budget-friendly vehicles that meet your needs.\n",
      "\n",
      "\n",
      "Agent: Thinking...\n",
      "Agent: It looks like I couldn't find any vehicles currently listed under $15,000. This could be due to a limited inventory or the specific types available. \n",
      "\n",
      "Here are a few next steps you can consider:\n",
      "\n",
      "1. **Expand Your Budget**: If possible, consider increasing your budget slightly. This could open up more options for you.\n",
      "\n",
      "2. **Look for Used Vehicles**: Sometimes, used vehicles can provide excellent value. Would you like me to focus on used cars or specific brands?\n",
      "\n",
      "3. **Different Vehicle Types**: Consider different types of vehicles (sedans, SUVs, trucks, etc.). This could also expand your options.\n",
      "\n",
      "Please let me know how you’d like to proceed or if there’s anything specific you’re looking for!\n",
      "\n",
      "\n",
      "Agent: Thinking...\n",
      "Agent: It looks like there are currently no available vehicles under $20,000. Would you like to adjust your budget or specify any particular types of vehicles you're interested in? This could help me find options that might suit your needs better!\n",
      "\n",
      "\n",
      "Agent: Thinking...\n",
      "Agent: Here are some great vehicle options under $30,000 that fit a variety of needs:\n",
      "\n",
      "### 1. **Toyota Camry**\n",
      "- **Price**: $28,000\n",
      "- **Year**: 2024\n",
      "- **Type**: Sedan\n",
      "- **Fuel Efficiency**: 28 MPG city / 39 MPG highway\n",
      "- **Safety Rating**: 5 stars\n",
      "- **Seating Capacity**: 5\n",
      "- **Key Features**: \n",
      "  - Backup Camera\n",
      "  - Bluetooth\n",
      "  - Lane Assist\n",
      "  - Adaptive Cruise Control\n",
      "- **Description**: A reliable family sedan with excellent fuel economy and top-notch safety features.\n",
      "\n",
      "### 2. **Hyundai Elantra**\n",
      "- **Price**: $22,000\n",
      "- **Year**: 2024\n",
      "- **Type**: Compact Sedan\n",
      "- **Fuel Efficiency**: 33 MPG city / 43 MPG highway\n",
      "- **Safety Rating**: 4 stars\n",
      "- **Seating Capacity**: 5\n",
      "- **Key Features**: \n",
      "  - 10-year Warranty\n",
      "  - Touchscreen\n",
      "  - Rear Camera\n",
      "  - Smart Key\n",
      "- **Description**: An affordable compact sedan with excellent warranty coverage and fuel efficiency.\n",
      "\n",
      "### Next Steps\n",
      "1. **Visit the Dealership**: Both vehicles are in stock, so you can schedule a visit to test drive them.\n",
      "2. **Consider Your Needs**: Think about which features are most important for you—fuel efficiency, safety ratings, or warranties.\n",
      "3. **Ask for Financing Options**: If you're considering financing, be sure to discuss options with the dealer.\n",
      "\n",
      "Would you like more details on either of these vehicles or assistance with anything else?\n",
      "\n",
      "\n",
      "Agent: Thinking...\n",
      "Agent: I can help you find vehicles based on specific criteria like budget, type, features, or priorities. Could you please provide me with some information about what you’re looking for? For example:\n",
      "\n",
      "1. **Budget Range:** What is your budget?\n",
      "2. **Vehicle Type:** Are you looking for a sedan, SUV, truck, etc.?\n",
      "3. **Features:** Any specific features you want?\n",
      "4. **Priorities:** Are you more focused on budget, family needs, luxury, or fuel efficiency? \n",
      "\n",
      "Let me know how I can assist you!\n",
      "\n",
      "\n",
      "Agent: Thinking...\n",
      "Agent: To help you find the best family-oriented vehicle, I’ll need a bit more information:\n",
      "\n",
      "1. **Budget**: What’s your price range?\n",
      "2. **Size Preference**: Do you prefer a minivan, SUV, or another type of vehicle?\n",
      "3. **Features**: Are there any specific features you’re looking for, such as safety ratings, space for car seats, or entertainment options?\n",
      "\n",
      "Once I have this information, I can provide tailored recommendations!\n",
      "\n",
      "\n",
      "Agent: Thinking...\n",
      "Agent: To help you find vehicles with high safety ratings, I'll focus on the family-oriented aspect since safety is often a priority for families. Let's look into some vehicles that are recognized for their excellent safety features and ratings.\n",
      "\n",
      "Can you please provide me with:\n",
      "1. Your budget range (if you have one in mind)?\n",
      "2. Any specific vehicle types you're interested in (like SUVs, sedans, etc.)?\n",
      "3. Any additional features that are important to you? \n",
      "\n",
      "This will help me provide the best recommendations for you!\n",
      "\n",
      "Thanks for using the Vehicle Recommendation System!\n"
     ]
    }
   ],
   "source": [
    "await run_interactive_demo_async()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### End of Notebook"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
